/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zwu.util;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.RepositoryException;

/**
 *
 * @author zwu
 */
public class CreateDeepNode {

    public static void create( Node root, URL url) throws javax.jcr.RepositoryException, java.io.UnsupportedEncodingException {

        String path = url.getPath();
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        final String host = url.getHost();
        List folderNames = new ArrayList();
        folderNames.addAll(Arrays.asList(host.split("\\.")));
        Collections.reverse(folderNames);
        folderNames.addAll(Arrays.asList(path.split("/", 0)));
        System.out.println(folderNames);

        final String fileName = URLDecoder.decode((String) folderNames.remove(folderNames.size() - 1), "UTF-8").replaceAll(":", "_");
        Node node = root;
        for (Iterator fn = folderNames.iterator(); fn.hasNext();) {
            String name = URLDecoder.decode((String) fn.next(), "UTF-8");
            name = name.replaceAll(":", "_");
            if (name.length() == 0) {
                continue;
            }
            if (!node.hasNode(name)) {
                node.addNode(name, "nt:folder");
            }
            node = node.getNode(name);
        }

    }

    public static  Node createDeepPath(Node root, String path) throws javax.jcr.RepositoryException
    {
        Node node = root;
        String[] folders = path.split("/");
        for (String p: folders)
        {
            p = p.replaceAll(":", "_");
            if (p.length() == 0)
                continue;
            if (!node.hasNode(p)) {
                node.addNode(p, "nt:folder");
            }
            node = node.getNode(p);
        }

        return node;
    }
    
    public static void main(String s[]) throws Exception
    {
        //create(new URL("http://www.tweddle.com/try");
    }
}
